import 'package:flutter/material.dart';
import 'package:flutter_easylogger/flutter_logger.dart';
import 'package:get/get.dart';

import '../../config/router_page_name.dart';
import '../../http/http_service.dart';
import '../../models/login_model.dart';
import '../../utils/user_info_utils.dart';
import '../../widgets/finger_print_scan_dialog.dart';

class LoginAccountLogic extends GetxController {

  TextEditingController accountController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  final httpService = HttpService();

  @override
  void onInit() {
    super.onInit();

    // 检查是否有传入的账号密码参数
    if (Get.arguments != null && Get.arguments is Map<String, dynamic>) {
      final args = Get.arguments as Map<String, dynamic>;

      Logger.d('Found arguments: $args');

      if (args.containsKey('username')) {
        accountController.text = args['username'];
        Logger.d('Set username: ${accountController.text}');
      }

      if (args.containsKey('password')) {
        passwordController.text = args['password'];
        Logger.d('Set password: ${passwordController.text}');
      }
    }
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    accountController.dispose();
    passwordController.dispose();
    super.onClose();
  }

  void toLogin() async {
    await Get.dialog(
      const FingerPrintScanDialog(),
      barrierColor: Colors.black38,
      barrierDismissible: false,
    );

    // 请求的数据
    final loginData = {
      'username': accountController.text,
      'password': passwordController.text,
    };

    final response = await httpService.post('/user/login', data: loginData);

    if (response.statusCode == 200) {
      Logger.e('登录成功');

      var responseData = response.data;

      // 创建登录模型并保存
      LoginModel loginModel = LoginModel.fromJson(responseData);
      DataUtils().saveUserInfo(loginModel);

      // 根据用户类型跳转到不同的页面
      // 使用同一个路由，但确保AppLogic会重新初始化
      Get.offAllNamed(RouterPageName.appPage);
    } else {
      var errorData = response.data;
      String errorMessage = "登录失败，请重试";

      if (errorData is Map<String, dynamic>) {
        errorMessage = errorData['message'] ?? errorData['error'] ?? errorMessage;
      } else if (errorData is String) {
        errorMessage = errorData;
      }

      Logger.e('登录失败: $errorMessage');
      Get.snackbar("错误", errorMessage);
    }
  }
}